<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Local\DcsData AS LocalDcsData;       //本地数据模型
use App\Models\Headquarters\DcsData AS HQDcsData;       //总部数据模型
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Log;

/**
 * 上报本地DCS数据到总部
 */
class DcsDataReportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $local_conn; //本地连接
    protected $remote_conn; //总部连接
    protected $local_data_table; //本地保存的原始数据集合
    protected $remote_data_table; //总部保存的数据集合

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params=null)
    {
        $this->local_conn = $params && isset($params['local_conn']) ? $params['local_conn'] : '';
        $this->remote_conn = $params && isset($params['remote_conn']) ? $params['remote_conn'] : '';
        $this->local_data_table = $params && isset($params['local_data_table']) ? $params['local_data_table'] : '';
        $this->remote_data_table = $params && isset($params['remote_data_table']) ? $params['remote_data_table'] : '';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $localDcsDataObj = (new LocalDcsData())->setConnection($this->local_conn)->setTable($this->local_data_table);
        $hQDcsDataObj = (new HQDcsData())->setConnection($this->remote_conn)->setTable($this->remote_data_table);
        $notReportDataList = $localDcsDataObj->findNotReport();

        try {
            foreach($notReportDataList as $row){
                $param = array(
                    'id' => $row->id,
                    'tag_name' => $row->tag_name,
                    'value'=> $row->value,
                    'datetime'=> $row->datetime
                );
                $res = $hQDcsDataObj->insertOne($param);
                if($res){
                    $row->flag = 1;
                    $row->save();
                }
            }
        } catch (QueryException $e) {
            Log::info(var_export($e, true));
            Log::info('=========上报总部DCS数据失败=========');
            DB::rollback();
        }
    }
}
